import server from './server.js';
import type { AxiosRequestConfig } from 'axios';
// import { mgop } from '@aligov/jssdk-mgop';

interface UrlListI {
    [index: string]: {
        url: string;
        type: string;
        config?: AxiosRequestConfig;
    };
}
interface callConfigI extends AxiosRequestConfig {
    success?: object;
    error?: object;
}
interface PluginI {
    include?: string[];
    exclude?: string[];
    beforeSend?: Function;
    afterSend?: Function;
}

function myAxios(this: any) {
    this.server = server;
    this.pluginsList = [];
}
myAxios.prototype.registApi = function (urlList: UrlListI) {
    Object.keys(urlList).forEach(apiName => {
        this[apiName] = (params: object, config: object) => {
            return this.send.call(this, apiName, urlList[apiName].url, urlList[apiName].type, urlList[apiName].config, params, config);
        };
    });
};
myAxios.prototype.send = function (
    apiName: string,
    url: string,
    type: string,
    statementConfig: AxiosRequestConfig = {}, // 在注册时传入的配置
    data: any = {},
    callConfig: callConfigI = {} //在调用时传入的配置
) {
    const config = Object.assign(statementConfig, callConfig);
    if (config.success) delete config.success;
    if (config.error) delete config.error;

    //#region //! 接口执行前后的方法
    const beforeSendArr: Function[] = [];
    const afterSendArr: Function[] = [];
    const pluginsData = {
        url: url,
        apiName: apiName,
        data
    };
    const successHandle =
        callConfig.success ||
        function (res: any) {
            return res;
        };
    const errorHandle =
        callConfig.error ||
        function (err: any) {
            return Promise.reject(err);
        };
    this.pluginsList.forEach((plugin: PluginI) => {
        if (
            (plugin.include && plugin.include.indexOf(apiName) != -1) ||
            (plugin.exclude && plugin.exclude.indexOf(apiName) == -1) ||
            (!plugin.include && !plugin.exclude)
        ) {
            plugin.beforeSend && beforeSendArr.push(plugin.beforeSend);
            plugin.afterSend && afterSendArr.push(plugin.afterSend);
        }
    });
    // let isFile = false; // 浙里办相关
    function beforeSendRun(this: any) {
        beforeSendArr.forEach(fn => {
            const _pluginsData = fn.call(this, pluginsData);
            // if (_pluginsData.newData) params = _pluginsData.newData;
            if (_pluginsData.newUrl) url = _pluginsData.newUrl;
            // if (_pluginsData.isFile) isFile = true; // 浙里办相关
        });
    }
    function afterSendRun(this: any, res: any) {
        let result = res;
        //! 对返回的数据加工修改
        afterSendArr.forEach(fn => {
            result = fn.call(this, result);
        });
        return result;
    }
    beforeSendRun();
    //#endregion

    // 浙里办相关
    // let axiosPromise
    // if (publicConfig.isMgop) axiosPromise = this.mgop.call(this, type, url, data, config, isFile);
    // else axiosPromise = this[type].call(this, url, data, config);
    const axiosPromise = this[type].call(this, url, data, config);

    return axiosPromise.then(afterSendRun).then(successHandle).catch(errorHandle);
};

// get方法
myAxios.prototype.get = function (url: string, data: object, _config: AxiosRequestConfig) {
    const config = Object.assign(_config, { params: data });
    return this.server.get(url, config);
};
// delete方法
myAxios.prototype.delete = function (url: string, data: object, _config: AxiosRequestConfig) {
    const config = Object.assign(_config, { params: data });
    return this.server.delete(url, config);
};
// post方法
myAxios.prototype.post = function (url: string, data: any, config: AxiosRequestConfig) {
    return this.server.post(url, data, config);
};
// put方法
myAxios.prototype.put = function (url: string, data: any, config: AxiosRequestConfig) {
    return this.server.put(url, data, config);
};

// 浙里办方法
// myAxios.prototype.mgop = function (type: string, url: string, data: object, config: object, isFile: boolean) {
//     let params: any;
//     if (type == 'get' || type == 'delete') {
//         params = qs.stringify(data);
//     }
//     return new Promise((re, rj) => {
//         mgop({
//             api: `mgop.zjxy.lwzj.${!isFile ? 'forwardJson' : 'forwardFile'}`, // RPC添加的API名称
//             host: 'https://dmtg.wenzhou.gov.cn:8068/',
//             dataType: 'JSON',
//             type: 'POST',
//             data: !isFile
//                 ? {
//                       json: type == 'post' || type == 'put' ? (typeof data == 'string' ? data : JSON.stringify(data)) : '',
//                       method: type.toUpperCase(),
//                       url: type == 'get' || type == 'delete' ? `${url}?${params}` : url
//                   }
//                 : data,
//             appKey: 'bjk7iv83+20014551+zihcqybt', // 必须
//             onSuccess: (res: any) => {
//                 console.log('onSuccess', res);
//                 re(res.data);
//             },
//             onFail: (err: any) => {
//                 console.log('onFail', err.errorMessage);
//                 rj(err.errorMessage);
//             }
//         });
//     });
// };

// 加入插件
myAxios.prototype.addPlugins = function (plugins: PluginI) {
    this.pluginsList.push(plugins);
};
export default new (myAxios as any)();
